package com.asj.vivo.lock.service.command.specific;

import static com.asj.enums.DeviceIdentifierDictEnums.appVersionDeviceReceiptTime;
import static com.asj.enums.DeviceIdentifierDictEnums.appVersionUpdate;
import static com.asj.enums.DeviceIdentifierDictEnums.appVersionUpdateStep;
import static com.asj.enums.DeviceIdentifierDictEnums.deviceUpdateCompletionTime;
import static com.asj.enums.HttpRequestDictEnums.receiveUpdateAppVersionUrl;
import static com.asj.enums.ResultCodeEnums.request_error;
import static com.asj.enums.ResultCodeEnums.result_error;
import static com.asj.enums.ResultCodeEnums.result_success;

import android.content.Context;
import android.util.Log;

import com.asj.service.updateService.UpdateAppVersionService;
import com.asj.utils.HttpRequestUtils;
import com.asj.utils.JSONParamPackingUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 版本更新推送
 * */
public class SpecificAppVersionUpdateService {
    public static void appVersionUpdate(JsonObject contentData, Context context){
        //包含更新url，更新的versionNumber，deviceId，deviceCode
        JsonObject appVersionUpdateInfo = JsonParser.parseString(contentData.get(appVersionUpdate.getValue()).getAsString()).getAsJsonObject();
        //接收到信息的时间
        contentData.addProperty(appVersionDeviceReceiptTime.getValue(), LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        try{
            //指定版本推送更新方法
            UpdateAppVersionService.assignVersionUpdate(context, appVersionUpdateInfo);
            //待更新方法走完，获取其中的步骤条，记录更新到哪一步
            Map<Integer, String> updateStep = UpdateAppVersionService.updateStep;
            contentData.addProperty(appVersionUpdateStep.getValue(),updateStep.toString());
            contentData.addProperty(deviceUpdateCompletionTime.getValue(), LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            JSONParamPackingUtils.functionPacking(contentData,result_success,null);
        }catch (Exception e){
            JSONParamPackingUtils.functionPacking(contentData,result_error,e.getMessage());
        }
        new Thread(()->{
            //将请求发送回去
            String result = HttpRequestUtils.retryHttpRequest(receiveUpdateAppVersionUrl.getValue(), contentData.toString(), result_success.getCode(), 5,context);
            if(!result.equals(request_error.getMessage())){
                Log.i("版本更新推送已返回结果，告知成功！",result);
            }
        }).start();
    }
}
